import BeforeSend from './beforeSend'
import listener from './listens/index'

let IPC = window.ipc

type EventParamsType = {
    success: boolean,
    value: any,
    next: string
}

export class Exchange{
    constructor(){
        IPC = window.ipc
        IPC.on('exchange', listener.route )
    }

    onEvent( eventName: string, handle : Function){
        IPC.on(eventName, handle || (()=>{}) )
    }

    removeEvent( eventName: string, handle:Function ){
        IPC.removeListener(eventName, handle)
    }

    // exchangeHandler(message:string){
    //     const args = Array.prototype.slice.call(arguments, 1)
    //     const msgTag = message.replace(/\-/g, '_');
    //     if( Listens[msgTag] instanceof Function){
    //         const re = Listens[msgTag].apply( this, args )
    //         return re
    //     }
    //     return null
    // }

    putInvoke( message: string ): Promise <string | null>{
        const args = Array.prototype.slice.call(arguments, 1)
        return IPC.invoke( message, ...args );
    }

    put(message: string, params: any = null ): any {
        const args = Array.prototype.slice.call(arguments, 1)
        return IPC.send( message, ...args )
    }

    asyncPut(message: string ): EventParamsType{
        const args = Array.prototype.slice.call(arguments, 1)
        const key: string = ( 'before_' + (message||'') )
        let p = args
        if( BeforeSend[key] instanceof Function){
            p = BeforeSend[key].apply( this, args )
        }
        return IPC.sendSync( message, ...p)
    }
}

export default Exchange